/**
 *
 * 添加比赛v2
 *
 * 任务 接受客户端传过来的数据验证并保持数据库
 *
 *
 */

module.exports = class extends think.Service
{

    constructor(ctx)
    {
        super(ctx);
        this.CPData = {};
        this.Steps = [];
        this.Judger = [];//裁判中间表
        this.AwardsItems = [];
        this.JudgerData = [];//裁判数据
        this.isErr = false;//false 表示没有错误
        this.errNo = 0;// 0 无错误
        this.errMsg = '操作成功'; // 错误信息
        this.hasAwardItems = false; //是否有获奖项目
    }


    /**
     * 获取比赛数据
     * @param postData
     * @returns {*}
     */
    resolveData(postData)
    {
        this._getCompetitionPostData(postData);
        if (this.isErr === true)
        {
            return {
                'isErr': this.isErr,
                'errNo': this.errNo,
                'errMsg': this.errMsg
            }

        } else
        {
            return {
                'isErr': this.isErr,
                'errNo': 0,
                'errMsg': 'ok'
            }
        }
    }


    async addAllData()
    {
        this._createInstance = this.model('apiv1/createCompetitionV2');

        //添加四类数据

        let rmsg = await this._createInstance.saveCompeititonData(this.CPData, this.Steps, this.AwardsItems, this.Judger, this.hasAwardItems,this.JudgerData);

        if (rmsg.errNo === 0)
        {
            this.isErr = false;
            this.errNo = 0;// 0 无错误
            this.errMsg = '添加成功'; // 错误信息
        } else
        {
            this.isErr = true;
            this.errNo = rmsg.errNo;// 0 无错误
            this.errMsg = rmsg.errMsg; // 错误信息
        }

        return {
            'isErr': this.isErr,
            'errNo': this.errNo,
            'errMsg': this.errMsg,
            'cpGuid': this.CPData.PK_CompetitionGuid
        }


    }


    /**
     * 获取cpdata
     */
    _getCompetitionPostData(postData)
    {
        /*
        需要三类信息:
        1.比赛基本信息
        2.比赛流程
        3.评委信息
         */
        this._getCompetitionDbData(postData);//数据对得上
        let cpsteps = postData['steps'];
        for (let index in cpsteps)
        {
            this._getStepsDbData(cpsteps[index]);
        }

    }

    /**
     * 获取cpdata的真实方法
     * @param postData
     * @private
     */
    _getCompetitionDbData(postData)
    {

        let Obj = {};
        Obj.PK_CompetitionGuid = think.uuid('v1');
        Obj.Title = postData.Title;//标题
        Obj.Desc = postData.Desc;//比赛描述
        Obj.CoverUrl = postData.CoverUrl;
        Obj.HeadCount = postData.HeadCount;
        Obj.ApplyNotes = postData.ApplyNotes;
        Obj.GameStartTime = postData.GameStartTime;
        Obj.GameEndTime = postData.GameEndTime;
        Obj.ApplyType = postData.ApplyType;
        if (postData.GameShowsType == '本平台发布')
        {
            Obj.GameShowsType = postData.GameShowsType;
            Obj.GameShowsContent = postData.GameShowsContent;
        } else if (postData.GameShowsType == '第三方发布')
        {
            Obj.GameShowsType = postData.GameShowsType;
            Obj.ShowsUrl = postData.ShowsUrl;
        }
        Obj.ApplyStartTime = postData.ApplyStartTime;
        Obj.ApplyEndTime = postData.ApplyEndTime;
        Obj.Status = '进行中';
        Obj.IsDelete = '未删除';
        this.CPData = Obj;
        return;
    }

    /**
     * 添加比赛时获取比赛步骤中的裁判
     * @param cpStepsGuid
     * @param judgerData
     * @returns {*}
     */
    _getJudgerDbData(cpStepsGuid, judgerData)
    {
        let judgerGuid = think.uuid('v1');
        let csj = think.uuid('v1');
        let judgerRules = {
            Name: {type: 'string', min: 1},
            Tel: {type: 'string', min: 5, max: 13},
            UserName: {type: 'string', min: 1},
            Password: {type: 'string', min: 1},
        };
        let bbase = think.validate(judgerData, judgerRules);
        if (bbase !== true)
        {
            this.isErr = true;
            this.errNo = 52040;// 0 无错误
            this.errMsg = bbase[0].message;
            return;
        };
        this.JudgerData.push({
            PK_JudgerGuid: judgerGuid,
            Name: judgerData.Name,
            Tel: judgerData.Tel,
            UserName: judgerData.UserName,
            Password: judgerData.Password,
            IsDelete: '未删除',
            Status: '有效',
        });
        this.Judger.push({
            'PK_CompetitionStepsToJudgerGuid': csj,
            'FK_JudgerGuid': judgerGuid,
            'FK_CompetitionStepsGuid': cpStepsGuid

        });


    }


    /**
     * 获取比赛步骤的真实方法
     * @param stepsObj
     * @returns {{status: boolean, errNo: string, errmsg: string}}
     */
    _getStepsDbData(stepsObj)
    {
        let obj = stepsObj;
        let dbStepsObj = {};
        let stepRule={
            Title:{type:'string',min:1},
            Content:{type:'string',min:1},
            Type:{type:'string',enum:['晋级','颁奖']},
            SubmitWorks:{type:'string',enum:['提交作品','不提交作品']},
            IsShowWorks:{type:'string',enum:['展示作品内容','发布结果','展示作品内容并发布结果']},
        };

        let bbase=think.validate(stepsObj,stepRule);
        if(bbase!==true){
            this.isErr = true;
            this.errNo = 52040;// 0 无错误
            this.errMsg = bbase[0].message; // 错误信息
            return;
        }
        //比赛步骤类型
        dbStepsObj.FK_CompetitionGuid = this.CPData.PK_CompetitionGuid;
        dbStepsObj.PK_CompetitionStepsGuid = think.uuid('v1');

        dbStepsObj.Title = obj.Title;
        dbStepsObj.Content = obj.Content;
        dbStepsObj.Type = obj.Type;
        dbStepsObj.QualifiedPerson = obj.QualifiedPerson | 0;
        //AwardsItems 不存在
        dbStepsObj.SubmitWorks = obj.SubmitWorks;
        dbStepsObj.IsShowWorks = obj.IsShowWorks;
        dbStepsObj.Status="进行中";
        //根据情况组装数据
        if (dbStepsObj.Type == '晋级')
        {
            if (dbStepsObj.QualifiedPerson < 1)
            {
                this.isErr = true;
                this.errNo = 52008;// 0 无错误
                this.errMsg = '比赛步骤为晋级时,晋级人数必须大于0'; // 错误信息
                return;
            }
        } else if (dbStepsObj.Type == '颁奖')
        {

            if (obj.AwardsItems.length < 1)
            {
                this.isErr = true;
                this.errNo = 52009;// 0 无错误
                this.errMsg = '比赛步骤为颁奖时,奖项必须存在并且大于1个或奖项提交格式错误'; // 错误信息
                return;
            }

            let flag = false;
            for (let i = 0; i < obj.AwardsItems.length; i++)
            {
                if (!think.isObject(obj.AwardsItems[i]))
                {
                    flag = true;
                }
            }
            if (flag)
            {
                this.isErr = true;
                this.errNo = 52009;// 0 无错误
                this.errMsg = '比赛步骤为颁奖时,奖项必须存在并且大于1个或奖项提交格式错误'; // 错误信息
                return;
            }
            this.hasAwardItems = true;
            this._getAwardsItemsDbData(obj.AwardsItems, dbStepsObj.PK_CompetitionStepsGuid);

        }
        //处理裁判
        let judgerArr = obj.Judger;
        for (let item in judgerArr)
        {
            this._getJudgerDbData(dbStepsObj.PK_CompetitionStepsGuid, judgerArr[item]);
        }

        this.Steps.push(dbStepsObj);
        //给对象赋上所有的值

    }


    _getAwardsItemsDbData(AwardsItems, cpStepsGuid)
    {
        for (let item in AwardsItems)
        {
            let awardDbData = {};

            let obj = AwardsItems[item];
            awardDbData.Title = obj['AwardsName'];
            awardDbData.FK_CompetitionStepsGuid = cpStepsGuid;
            awardDbData.Num = obj['AwardsPeoples'];
            if (think.isString(awardDbData.Title) && think.isString(awardDbData.FK_CompetitionStepsGuid) && think.isNumber(awardDbData.Num))
            {
                this.AwardsItems.push(awardDbData);
            } else
            {
                this.isErr = true;
                this.errNo = 52003;// 0 无错误
                this.errMsg = '奖项错误,请检查AwardsItems,该参数必须为数组,数组的元素必须为对象'; // 错误信息
                return;
            }

        }
        return;
    }

    /**
     * 获取作品数量 finish
     * @param guid
     * @returns {Promise.<number|wkc>}
     */
    async getWorksCountByWorksGuid(guid)
    {
        this.cpStepsInstance = think.model('apiv1/competitionSteps');
        this.wsNoInstance = think.model('apiv1/workSno');
        this._worksCount = 0;

        /*
           算法:
           1,首先查出该比赛里有哪些步骤
           2,计算每个步骤里有多少作品并相加
        */

        let cpStepsData = await this.cpStepsInstance.getStepsByGuid(guid);
        if (!think.isEmpty(cpStepsData))
        {
            for (let index in cpStepsData)
            {
                let stepGuid = cpStepsData[index]['PK_CompetitionStepsGuid'];
                let wkc = await this.wsNoInstance.getWorksCountByWorkStepsGuid(stepGuid);
                this._worksCount += wkc;
            }
        }
        return this._worksCount;
    }


    async getCPWorksCountByWorksGuid(workGuid)
    {
        this.cpStepsInstance = think.model('apiv1/competitionSteps');
        this.wsNoInstance = think.model('apiv1/competitionsteptoworks');
        this._worksCount = 0;

        /*
           算法:
           1,首先查出该比赛里有哪些步骤
           2,计算每个步骤里有多少作品并相加
        */

        let cpStepsData = await this.cpStepsInstance.getCPStepsByCPGuid(workGuid);
        for (let index in cpStepsData)
        {
            let stepGuid = cpStepsData[index]['PK_CompetitionStepsGuid'];
            let wkc = await this.wsNoInstance.getWorksCountByWorkStepsGuid(stepGuid);
            this._worksCount += wkc;
        }
        return this._worksCount;
    }

};